package cloud.mist.sailonix.controller;

import cloud.mist.sailonix.common.Result;
import cloud.mist.sailonix.entity.User;
import cloud.mist.sailonix.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器 - 分库分表测试接口
 */
@Tag(name = "用户管理", description = "用户管理相关接口 - 分库分表测试")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 创建用户
     */
    @Operation(summary = "创建用户", description = "创建单个用户并保存到分库分表中")
    @PostMapping
    public Result<User> createUser(@RequestBody User user) {
        User savedUser = userService.saveUser(user);
        return Result.success("用户创建成功", savedUser);
    }

    /**
     * 根据ID查询用户
     */
    @Operation(summary = "根据ID查询用户", description = "根据用户ID从分库分表中查询用户")
    @GetMapping("/{id}")
    public Result<User> getUser(@Parameter(description = "用户ID", example = "123456789") @PathVariable Long id) {
        User user = userService.getUserById(id);
        return Result.success("查询成功", user);
    }

    /**
     * 查询所有用户
     */
    @Operation(summary = "查询所有用户", description = "查询所有分库分表中的用户")
    @GetMapping
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success("查询成功", users);
    }

    /**
     * 根据用户名查询
     */
    @Operation(summary = "根据用户名查询", description = "根据用户名模糊查询用户")
    @GetMapping("/search")
    public Result<List<User>> searchUsers(@Parameter(description = "用户名", example = "zhangsan") @RequestParam String username) {
        List<User> users = userService.getUsersByUsername(username);
        return Result.success("查询成功", users);
    }

    /**
     * 批量创建用户
     */
    @Operation(summary = "批量创建用户", description = "批量创建用户并分配到分库分表中")
    @PostMapping("/batch")
    public Result<String> batchCreateUsers(@RequestBody List<User> users) {
        userService.batchSaveUsers(users);
        return Result.success("批量创建用户成功", "批量创建用户成功");
    }

    /**
     * 统计用户数量
     */
    @Operation(summary = "统计用户数量", description = "统计所有分库分表中的用户总数")
    @GetMapping("/count")
    public Result<Long> countUsers() {
        Long count = userService.countUsers();
        return Result.success("统计成功", count);
    }
}